package com.lans.search;

/**
 * @author: lans
 * @date: 2025/3/10
 * @name: 刘宇
 */
public class InsertSearch {
    public static void main(String[] args) {
        //二分查找算法的前提是一个有序的序列
        int[] arr = {10,21,32,42,543,6575,4354546};
        int search = search(arr,0,arr.length-1,543);
        System.out.println("search = " + search);
    }
    public static int search(int[] arr, int left, int right, int target) {
        //防止数组越界
        if(left>right || target<arr[0]||target>arr[arr.length-1]) {
            return -1;
        }
        //求出mid的结果
        int mid = left+(right-left)*(target-arr[left])/(arr[right]-arr[left]);
        //求出mid对应的值
        int midVal = arr[mid];
        if(target>midVal) {
            return search(arr,mid+1,right,target);
        }else if(midVal>target) {
            return search(arr,left,mid-1,target);
        }else{
            return mid;
        }
    }
}